﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;
using DCS.Business.Manager;
using DCS.DataProvider;
using DCS.Business.Model;
using DCS.Business.Interface;
using CarolLib.Core.Helper;
using PFSSyncer.ESB;
using System.IO;
using MessagerSync;

namespace DCS.BusinessObject
{
    public class Syncer : SyncerBase
    {


        #region Implete abstract Methods
        /// <summary>
        /// 调webservice
        /// </summary>
        /// <param name="esbparam"></param>
        /// <param name="esbheader"></param>
        public override void CallESBWS(object esbparam, SoapHeadInfo esbheader)
        {
            ESBTMPPPFSService service = new ESBTMPPPFSService();
            service.RequestEncoding = Encoding.UTF8;
            service.SoapVersion = System.Web.Services.Protocols.SoapProtocolVersion.Soap11;
            service.ESBHeader = ConvertHelper.ConvertObject<ESBHeadInfo, SoapHeadInfo>(esbheader);

            ESBTMPPPFSServiceResponse response = service.CallESBTMPPPFSService((ESBTMPPPFSService1)esbparam);
        }

        /// <summary>
        /// 构造soap参数
        /// </summary>
        /// <param name="group"></param>
        /// <param name="messagerList"></param>
        /// <param name="flightOnly"></param>
        /// <returns></returns>
        public override object GetESBParam(DCSFileGroup group, MessageGroup messagerList, bool flightOnly)
        {
            ESBTMPPPFSService1 result = new ESBTMPPPFSService1();
            List<PFS_Type> pfs = GetRelatedPFSs(group, messagerList.PFSList);

            result.PFSMessage = pfs.ToArray();

            return result;
        }
        #endregion


        private List<PFS_Type> GetRelatedPFSs(DCSFileGroup fileGroup, List<PFSMessage> pfsMessageList)
        {
            //lance add. 2011-6-17，fix empty transation bug.
            if (pfsMessageList.Count == 0)
            {
                List<PFS_Type> result = new List<PFS_Type>();
                PFS_Type pfs = new PFS_Type();
                pfs.Flight = new PFSFlight_Type();
                pfs.Flight.DepartureDate = fileGroup.DeptDate; 
                pfs.Flight.FNPostfix = string.Empty;
                pfs.Flight.BoardingAirport = fileGroup.DeptAirport;
                // Lance add the following code to fix the FlightNumber and FNPostfix issue.
                int tempint;
                if (int.TryParse(fileGroup.FlightNo, out tempint))
                {
                    pfs.Flight.FlightNumber = fileGroup.Carrier + fileGroup.FlightNo;
                    pfs.Flight.FNPostfix = string.Empty;
                }
                else
                {
                    pfs.Flight.FlightNumber = fileGroup.Carrier + fileGroup.FlightNo.Substring(0, fileGroup.FlightNo.Length - 1);
                    pfs.Flight.FNPostfix = fileGroup.FlightNo.Replace(fileGroup.FlightNo.Substring(0, fileGroup.FlightNo.Length - 1), string.Empty);
                }

                return result;
            }

            List<int> ids = fileGroup.Select(d => d.FileId).ToList();
            List<PFSMessage> pfsMessagesRelated = pfsMessageList.Where(p => ids.Contains(p.RefFileId)).ToList();

            List<PFS_Type> pfsList = pfsMessagesRelated.GroupBy<PFSMessage, int>(message => message.RefFileId)
                .Select(group1 =>
            {

                PFS_Type pfs = new PFS_Type();

                pfs.Flight = new PFSFlight_Type();
                pfs.Flight.BoardingAirport = fileGroup.DeptAirport;
                pfs.Flight.DepartureDate = fileGroup.DeptDate;
                // Lance add the following code to fix the FlightNumber and FNPostfix issue.
                int tempint;
                if (int.TryParse(fileGroup.FlightNo, out tempint))
                {
                    pfs.Flight.FlightNumber = fileGroup.Carrier + fileGroup.FlightNo;
                    pfs.Flight.FNPostfix = string.Empty;
                }
                else
                {
                    pfs.Flight.FlightNumber = fileGroup.Carrier + fileGroup.FlightNo.Substring(0, fileGroup.FlightNo.Length - 1);
                    pfs.Flight.FNPostfix = fileGroup.FlightNo.Replace(fileGroup.FlightNo.Substring(0, fileGroup.FlightNo.Length - 1), string.Empty);
                }

                pfs.CountInfoByAirport = group1.Select(message =>
                {
                    string[] bpCounts = message.BoardedPassenger.Trim().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                    string[] padPCounts = message.PadPassenger.Trim().Substring(4).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                    PFSAirportCount_Type PFSAirportCount = new PFSAirportCount_Type();
                    PFSAirportCount.DestinationAirport = message.ArrAirport;
                    int count = 0;
                    PFSAirportCount.BoardedPassenger = bpCounts.Select(c => new PFSCount_Type()
                    {
                        Count = int.TryParse(c, out count) ? count : 0,
                    }).ToArray();
                    PFSAirportCount.PADPassenger = padPCounts.Select(c => new PFSCount_Type()
                    {
                        Count = int.TryParse(c, out count) ? count : 0,
                    }).ToArray();
                    PFSAirportCount.Infant = new PFSCount_Type() { Count = message.Baby, };
                    return PFSAirportCount;

                }).ToArray();
                pfs.Configuration = group1.Select(message =>
                {
                    PFSCompartment_Type PFSCompartment = new PFSCompartment_Type();
                    PFSCompartment.CompartmentIdentifier = "";
                    PFSCompartment.CompartmentSeatsNumber = "";
                    return PFSCompartment;
                }).ToArray();
                pfs.LoadStatusByAirport = group1.Select(message =>
                {
                    PFSDestinationAirport_Type PFSDestinationAirport = new PFSDestinationAirport_Type();

                    PFSDestinationAirport.CategoryByStatusCode = message.PFSPassengers.GroupBy(p =>
                    {
                        PFSStatusCode_Type StatusCode = new PFSStatusCode_Type();
                        StatusCode.CategoryCode = p.StatusCode;
                        StatusCode.ClassIdentifier = p.Class;
                        StatusCode.PassengerNumber = p.ClassNum;
                        return StatusCode;
                    }, new PFSStatusCodeComparer()
                    ).Select(pg =>
                    {
                        PFSCategoryByStatusCode_Type PFSCategoryByStatusCode = new PFSCategoryByStatusCode_Type();
                        PFSCategoryByStatusCode.StatusCode = pg.Key;
                        PFSCategoryByStatusCode.Passenger = pg.Select(p =>
                        {
                            PFSPassengerInfo_Type PFSPassengerInfo = new PFSPassengerInfo_Type();
                            PFSPassengerInfo.FamilyName = p.PName.IndexOf('/') != -1 ? p.PName.Split('/')[0] : "";
                            PFSPassengerInfo.GivenName = p.PName.IndexOf('/') != -1 ? p.PName.Split('/')[1] : p.PName;
                            PFSPassengerInfo.FullName = p.PName;
                            PFSPassengerInfo.FFCardCode = new PFSFFCardInfo_Type()
                            {
                                AirlineCode = "",
                                CardLevel = "",
                                FFCardNo = "",
                            };
                            PFSPassengerInfo.PNR = p.PNR;
                            PFSPassengerInfo.PassengerId = new PFSPassengerId_Type()
                            {
                                FFPIdentification = "",
                                FirstNameInitialsTitle = "",
                                Surname = "",
                            };
                            PFSPassengerInfo.PassengerNumberBySurname = "";
                            PFSPassengerInfo.PreferredTitle = "";
                            return PFSPassengerInfo;
                        }).ToArray();
                        return PFSCategoryByStatusCode;
                    }).ToArray();
                    PFSDestinationAirport.DestinationAirport = message.ArrAirport;
                    return PFSDestinationAirport;
                }).ToArray();
                pfs.SharedFlightIdentifier = group1.First().SharedNo;
                string[] tpCounts = group1.First().TransitPassenger.Trim().Split(new char[] { '\x20' }, StringSplitOptions.RemoveEmptyEntries);
                //pfs.TransitInfo = new PFSTransitInfo_Type()
                //{
                //    TransitInfant = new PFSCount_Type()
                //    {
                //        Count = group1.First().TransitBaby,
                //    },
                //    TransitPassenger = tpCounts.Select(c => new PFSCount_Type
                //    {
                //        Count = int.Parse(c),
                //    }).ToArray(),
                //};
                pfs.TransitInfo = null;

                return pfs;
            }).ToList();

            return pfsList;
        }


    }

}
